#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <curses.h>
#include "caml.h"
#include "structures.h"
#include "init.h"
#include "keyboard.h"
#include "debug.h"
#include "tools.h"

value			init_context(value			ba,
				     value			color,
				     value			color_bg)
{
  int			i;
  p_context		c;
  int			*p;

  p = Data_bigarray_val(ba);
  c = malloc(sizeof (struct s_context));

  c->color = Int_val(color);
  c->color_bg = Int_val(color_bg);
  c->height_font = 1;
  c->width_font = 1;
  c->is_frame = 1;

  for (i = 0; i < MAX_WIN; i++)
    WIN[i] = NULL;

  NAME[ZONE_VIDEO] = NAME_VIDEO;
  NAME[ZONE_INFOBAR] = NAME_INFOBAR;
  NAME[ZONE_MENUBAR] = NAME_MENUBAR;
  NAME[ZONE_PLAYLIST] = NAME_PLAYLIST;
  NAME[ZONE_THUMB] = NAME_THUMB;
  NAME[ZONE_EXPLORER] = NAME_EXPLORER;

  DESCR[ZONE_VIDEO] = DESCR_VIDEO;
  DESCR[ZONE_INFOBAR] = DESCR_INFOBAR;
  DESCR[ZONE_MENUBAR] = DESCR_MENUBAR;
  DESCR[ZONE_PLAYLIST] = DESCR_PLAYLIST;
  DESCR[ZONE_THUMB] = DESCR_THUMB;
  DESCR[ZONE_EXPLORER] = DESCR_EXPLORER;

  SIDE[ZONE_VIDEO] = NONE;
  SIDE[ZONE_INFOBAR] = BOTTOM;
  SIDE[ZONE_MENUBAR] = TOP;
  SIDE[ZONE_PLAYLIST] = RIGHT;
  SIDE[ZONE_EXPLORER] = LEFT;

  init_env(ba, c);
  p[IBA_CONTEXT] = c;
  p[IBA_UPDATE_WVIDEO] = 1;

  return (0);
}


void			init_curses_core(void)
{
  initscr();
  qiflush(); /* interflush; best response time; wrong display */
  curs_set(0); /* hide cursor [char] */
  noecho();
  keypad(stdscr, true); /* enable special keys */

  if (raw() == ERR) /* disable \r flush + catch sigs [instead of cbreak] */
  {
    printf("Init Failure (unable to call raw)\n");
    exit(30);
  }

  nodelay(stdscr, true); /* getch() isn't blocking anymore */
}


/* set ZONE_MAIN */
int			init_env(value				ba,
				 p_context			c)
{
  int			*p;

  init_curses_core();
  init_mouse();
  init_curses_color(c);

  p = Data_bigarray_val(ba);
  getmaxyx(stdscr, c->line, c->col);

  HEIGHT_MAIN = c->line;
  WIDTH_MAIN = c->col;

  HEIGHT_VIDEO = c->line;
  WIDTH_VIDEO = c->col;

  p[IBA_SCREEN_LINE] = c->line ;
  p[IBA_SCREEN_COL] = c->col;

  p[IBA_VIDEO_LINE] = c->line;
  p[IBA_VIDEO_COL] = c->col;

  WMAIN = newwin(c->line, c->col, 0, 0);
  WVIDEO = subwin(WMAIN, c->line, c->col, 0, 0);

  c->nb_win = 1;
  c->nb_display_files = 0;
  touchwin(WMAIN);

  return (0);
}


void			init_curses_color(p_context		c)
{
  int			i;

  if (0) /* /\* (Int_val(c->color)) *\/ grepme */
    return; /* color not requested */

  if (has_colors() == FALSE)
  {
    endwin();
    printf("This terminal does not support color\n");
    exit(30);
  }

  start_color();
  assume_default_colors(-1, -1);

  for (i = 0; i < 9; i++)
    init_pair(i, COLOR_BLACK + i - 1, -1); /* -1 : default background color */
}


void			init_mouse(void)
{
  if (has_mouse())
  {
    endwin();
    printf("This terminal does not support mouse\n");
    exit(30);
  }

  mousemask(ALL_MOUSE_EVENTS, NULL);
  return;
}
